package com.awspaas.user.apps.sts.controller;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.ProcessInstance;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.TaskInstance;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.org.model.UserModel;
import com.actionsoft.bpms.server.RequestParams;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.bind.annotation.Controller;
import com.actionsoft.bpms.server.bind.annotation.Mapping;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.awspaas.user.apps.publicservice.bean.*;
import com.awspaas.user.apps.sts.service.STSService;
import com.awspaas.user.apps.sts.service.StsBtnSevice;
import com.awspaas.user.apps.sts.util.MiddleLogUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @Title: StsBtnController
 * @Package com.awspaas.user.apps.sts.Controller.StsBtnController
 * @Description: 提交，保存按钮触发动作基础控制
 * @Author zhoujianchen
 * @Email
 * @Date 2022/9/04
 */
@Controller
public class StsBtnController {
    /**
     * 按钮点击后触发动作（提交，保存）
     * @param uc
     * @param re
     * @return
     */
    @Mapping("com.awspaas.user.apps.cmdc.prinft.BtnClickEvent")
    public String BtnClickEvent(UserContext uc, RequestParams re){
        return  new StsBtnSevice().BtnClickEvent(uc,re);
    }

    /**
     * 控制审批留言显隐
     * @param uc
     * @param re
     * @return
     */
    @Mapping("com.awspaas.user.apps.cmdc.prinft.MsgShowEvent")
    public String MsgShowEvent(UserContext uc, RequestParams re){
        return  new StsBtnSevice().MsgShowEvent(uc,re);
    }



    /**
     * 更新中间操作日志表
     * @param uc
     * @param re
     * @return
     */
    @Mapping("com.awspaas.user.apps.cmdc.prinft.updateMiddleLog")
    public String updateMiddleLog(UserContext uc, RequestParams re){
        Map<String, String> paramsMap = re.asMap();
        MiddleLogUtil middleLogUtil = new MiddleLogUtil();
        String updateBtnLogState = middleLogUtil.UpdateBtnLog(paramsMap);
        System.out.println("更新结果："+updateBtnLogState);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", updateBtnLogState);
        System.out.println("返回数据为："+jsonObject.toJSONString());
        return  jsonObject.toString();
    }

    @Mapping("com.awspaas.user.apps.cmdc.prinft.getSignBtnLogMax")
    public String getSignBtnLogMax(UserContext uc, RequestParams re){
        return  new StsBtnSevice().getSignBtnLogMax(uc,re);
    }

    @Mapping("com.awspaas.user.apps.cmdc.prinft.terminateProcess")
    public String terminateProcess(UserContext uc, RequestParams re){
        String processinstid = re.get("PROCESSINSTID");
        String sid = re.get("sid");
        //根据sid获取用户uid
        uc = UserContext.fromSessionId(sid);
        String targetUid = uc.getUID();
        //将所有参数放入
        RequestData requestData = new RequestData();
        requestData.setTargetUid(targetUid);
        requestData.setProcessInstId(processinstid);

        //定义返回值
        ResponseObject ro = ResponseObject.newOkResponse();
        STSService service = new STSService();
        HashMap<String, Object> responseMap = new HashMap<>();
        responseMap.put("PROCESSINSTID", processinstid);
        responseMap.put("TARGETUID", targetUid);
        responseMap.put("ISCANCLE", "cancelFailed");
        ro.put("data", responseMap);
        ResponseData responseData = new ResponseData();

        try {
            //判断流程实例是否存在BPM系统
            ProcessInstance getProcessInstance = SDK.getProcessQueryAPI().detailById(processinstid);
            if (null!=getProcessInstance) {
                //判断流程实例是否已经结束
                boolean endById = SDK.getProcessAPI().isEndById(processinstid);
                if (!endById) {
                    //判断当前节点是否允许终止流程
                    TaskInstance currentTask = SDK.getTaskQueryAPI().processInstId(processinstid).activeTask().detail();
                    String activityDefId = currentTask.getActivityDefId();
                    BO baBO = SDK.getBOAPI().query("BO_PS_BUSINESS_ACTIVITY", true).addQuery("ACTIVITY_DEFID = ", activityDefId).detail();
                    if (null!=baBO) {
                        String isallowterminate = baBO.getString("ISALLOWTERMINATE");
                        if (null==isallowterminate || isallowterminate.equals("") || isallowterminate.equals("01")) {
                            ResponseCode successRC = ResponseCode.SUCCESS_RESPONSE;
                            ro.put("code", successRC.getCode());
                            ro.put("desc", successRC.getDesc());
                            responseData = service.terminateProcess(requestData);
                            responseMap.put("PROCESSINSTID", responseData.getProcess_InstID());
                            responseMap.put("TARGETUID", responseData.getTargetUid());
                            responseMap.put("ISCANCLE", "cancel");
                            ro.put("data", responseMap);
                        } else {
                            ro.put("code", 500);
                            ro.put("desc", "当前流程节点不允许取消流程");
                        }
                    } else {
                        ro.put("code", 500);
                        ro.put("desc", "当前流程节点未维护至流程节点与业务状态规则表");
                    }
                } else {
                    ro.put("code", 500);
                    ro.put("desc", "当前流程已经结束");
                }
            } else {
                ro.put("code", 500);
                ro.put("desc", "BPM系统不存在当前流程实例");
            }
        }catch (Exception e){
            ro.put("code", 500);
            ro.put("desc", "流程取消错误");
        }
        return  ro.toString();
    }

    @Mapping("com.awspaas.user.apps.cmdc.prinft.rollbackTask")
    public String rollbackTask(UserContext uc, RequestParams re){

        String taskinstid = re.get("TASKINSTID");
        String commentmsg = re.get("COMMENTMSG");
        String sid = re.get("sid");
        //根据sid获取用户uid
        uc = UserContext.fromSessionId(sid);
        String targetUid = uc.getUID();

        //定义返回值
        STSService service = new STSService();
        ResponseObject ro = ResponseObject.newOkResponse();
        ResponseData responseData = service.rollbackTask(taskinstid,targetUid,commentmsg);
        ro.put("data", responseData);

        return  ro.toString();
    }


}
